package com.lixinxin.commoncomposeproject.view_model

import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lixinxin.commoncomposeproject.model.ArticleState
import com.lixinxin.commoncomposeproject.repository.ArticleRepository
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch

/**
 *   author ： lixinxin
 *   time    ： 2021-11-19
 *   email：895330766@qq.com
 */
class ArticleViewModel : ViewModel() {


    val articleData: MutableState<ArticleState> = mutableStateOf(ArticleState.Empty)


    init {
        getArticleData(1)
    }


    fun getArticleData(page: Int) {
        viewModelScope.launch {
            ArticleRepository.getArticle(page = page)
                .onStart {
                    articleData.value = ArticleState.Loading
                }
                .catch { e ->
                    articleData.value = ArticleState.Failure(e)
                }
                .collect { data ->
                    articleData.value = ArticleState.Success(data)
                }
        }
    }


}